<?php

namespace xhadmin\db;
use think\facade\App;
use \think\facade\Log;
use PhpOffice\PhpSpreadsheet\Cell\DataType;
use PhpOffice\PhpSpreadsheet\Style\Alignment;
use PhpOffice\PhpSpreadsheet\Style\Border;
use PhpOffice\PhpSpreadsheet\Writer\Xlsx;
use PhpOffice\PhpSpreadsheet\Spreadsheet;
use PhpOffice\PhpSpreadsheet\Worksheet\Drawing;

class Common
{

	//记录sql错误日志
	public static function setLog($msg){
		if(strpos($msg,'Duplicate') > 0){
			preg_match("/Duplicate entry '(.*)' for key '(.*)'/",$msg,$all);
			$fieldInfo = \app\admin\db\Field::getWhereInfo(['field'=>$all[2]]);
			if($fieldInfo){
				throw new \Exception($fieldInfo['name'].'已经存在!');
			}
		}
		log::error('sql错误：'.$msg);
	}

    public static function dumpData($headers,$data){
        try{
            $styleArray = [
                'borders' => [
                    'outline' => [
                        'borderStyle' => Border::BORDER_THICK,
                        'color' => ['argb' => '000000'],
                    ],
                    'inside' =>[
                        'borderStyle' => Border::BORDER_THICK,
                        'color' => ['argb' => '000000'],
                    ]
                ]
            ];
            $styleArray1 = [
                // 'borders' => [
                //     'outline' => [
                //         'borderStyle' => Border::BORDER_THICK,
                //         'color' => ['argb' => '000000'],
                //     ],
                //     'inside' =>[
                //         'borderStyle' => Border::BORDER_THICK,
                //         'color' => ['argb' => '000000'],
                //     ]
                // ],
                'alignment' => [
                    'horizontal' => Alignment::HORIZONTAL_CENTER,// 水平居中
                    'vertical' => Alignment::VERTICAL_CENTER //垂直居中
                ]
            ];
            /**************** 设置临时文件相关信息，并删除函数 *******************/
            $tmpFileList = [];  //临时文件，保存excel后需要删除
            $tmpFileDelFunc = function($tmpFileList) {
                foreach($tmpFileList as $file) {
                    @unlink($file);
                }
            };
            $tmpFilePath = App::getRootPath() . 'public/export/tmp/';
            /************** END 设置临时文件相关信息，并删除函数 *****************/

            $base_path=App::getRootPath().'public';
            //获取表头
            $title =array_column($headers,0);
            // Create new Spreadsheet object
            $spreadsheet = new Spreadsheet();
            $sheet = $spreadsheet->getActiveSheet();
            //默认行高
            $sheet->getDefaultRowDimension()->setRowHeight(17);
            //默认行宽
            $sheet->getDefaultColumnDimension()->setWidth(22);
            // 方法一，使用 setCellValueByColumnAndRow
            //表头
            //设置单元格内容
            foreach ($title as $key => $value) {
                // 单元格内容写入
                $sheet->setCellValueByColumnAndRow($key + 1, 1, $value);
            }
            $sheet->getRowDimension('1')->setRowHeight(30);
            $spreadsheet->getActiveSheet()->getStyle(int_to_chr(0).'1:'.int_to_chr(count($title)-1).'1')->getFont()->setBold(true)->setName('Arial')->setSize(10);

            $sheet->getStyle(int_to_chr(0).'1:'.int_to_chr(count($title)-1).'1')->applyFromArray($styleArray1);
            //        $sheet->getStyle(int_to_chr(0).'1:'.int_to_chr(count($title)-1).'1')->getFill()->setFillType(\PhpOffice\PhpSpreadsheet\Style\Fill::FILL_SOLID)->getStartColor()->setARGB('f0f0f0');

            //所有内容垂直居中
            $sheet->getStyle(int_to_chr(1).'1:'.int_to_chr(count($title)-1).(count($data) + 1))->applyFromArray([
                'alignment' => [
                    'vertical'  => Alignment::VERTICAL_CENTER //垂直居中
                ],
            ]);

            //     $sheet->getStyle(int_to_chr(0).'1:'.int_to_chr(count($title)-1).'1')->applyFromArray($styleArray1);
            $row = 2; // 从第二行开始
            foreach ($data as $item) {
                $column = 1;
                foreach ($item as $key=>$value) {
                    $value_type=isset($headers[$key][1]) ? $headers[$key][1] : '';
                    if(strtolower($value_type)=='img'){
                        $imgPath =explode('|', $value)[0];
                        $value=str_replace('\\','/',$base_path.$imgPath);
                        //通过域名方式获取图片地址
                        $domainGetValueFunc = function(&$isSaveFile) use($imgPath,$tmpFilePath) {
                            if(empty($imgPath)){    //图片不存在，返回 false
                                return false;
                            }
                            //获取域名地址
                            $getImgUrlFunc = function() use($imgPath) {
                                return url($imgPath,[],false,true);
                            };
                            $imgUrl = preg_match('/^http(s)?\:\/\//',$imgPath)?$imgPath:$getImgUrlFunc();
                            $filePath = $tmpFilePath . date('Ymd_') . rand(1000000,9999999) . '_' . basename($imgUrl);
                            if(!SELF::dlfile($imgUrl,$filePath)) {
                                return false;
                            }
                            $isSaveFile = true;
                            return $filePath;
                        };
                        $isSaveFile = false;
                        if(file_exists($value) || $value = $domainGetValueFunc($isSaveFile)) {
                            unset($drawing);
                            $drawing=new Drawing();
                            $drawing->setName('Logo');
                            $drawing->setDescription('Logo');
                            $drawing->setPath($value);
                            // $drawing->setWidth(30);
                            $drawing->setHeight(22);
                            $drawing->setCoordinates(int_to_chr($column-1).$row);
                            $drawing->setOffsetX(12);
                            $drawing->setOffsetY(5);
                            $drawing->setWorksheet($sheet);
                            // $sheet->getColumnDimension(int_to_chr($column-1))->setAutoSize(true);
                            if($isSaveFile) {
                                $tmpFileList[] = $value;
                            }
                        }
                    }elseif(strtolower($value_type)=='url' && !empty($value)){
                        //链接不为空
                        $sheet->setCellValueByColumnAndRow($column, $row, $value);
                        $sheet->getCell(int_to_chr($column-1).$row)->getHyperlink()->setUrl($value);
                    }else{
                        // 单元格内容写入
                        $sheet->setCellValueByColumnAndRow($column, $row, "\t".$value);
                    }
                    $sheet->getColumnDimension(int_to_chr($column-1))->setWidth(17);
                    $sheet->getRowDimension($row)->setRowHeight(22);
                    // $sheet->getStyle(int_to_chr($column-1).$row)->applyFromArray($styleArray);
                    $column++;
                }
                $row++;
            }
            //$sheet->getStyle('A:J')->applyFromArray($styleArray);// 外边框，内边框
            $filename = date('YmdHis');
//            header('Content-Type: application/vnd.openxmlformats-officedocument.spreadsheetml.sheet');
//            header('Content-Disposition: attachment;filename="'. $filename .'.xlsx"');
//            header('Cache-Control: max-age=0');
//            header('Expires: Mon, 26 Jul 1997 05:00:00 GMT'); // Date in the past
//            header('Last-Modified: ' . gmdate('D, d M Y H:i:s') . ' GMT'); // always modified
//            header('Cache-Control: cache, must-revalidate'); // HTTP/1.1
//            header('Pragma: public'); // HTTP/1.0

            $writer = new Xlsx($spreadsheet);

            $outdir = App::getBasePath().'../public/export/data';
            if(!is_dir($outdir)) {
                mkdir($outdir,'0755',true);
            }
            $file_nm = $filename.'.xlsx';
            $file = $outdir.'/'.$file_nm;
            fopen($file,"w+");
            $writer->save($file);
            $tmpFileDelFunc($tmpFileList);
            return $file_nm;
            //exit();
        }catch(\Exception $e){
            $tmpFileDelFunc($tmpFileList);
            throw new \Exception($e->getMessage());
        }
    }


}
